import { Get, Patch } from '@/axios'
import router from '@/router'
import store from '@/store'

import config from '../config'
const getUserInfoURL = `${config.host}/api/v5/user`
const notificationURL = `${config.host}/api/v5/notifications/threads`
const setReadNoticeURL = `${config.host}/api/v5/notifications/threads/:id`
const setReadUserMessageURL = `${config.host}/api/v5/notifications/messages/:id`
const getUserMessageURL = `${config.host}/api/v5/notifications/messages`

const getIssuesURL = `${config.host}/api/v5/repos/:owner/:repo/issues`
const getIssueURL = `${config.host}/api/v5/repos/:owner/:repo/issues/:number`
const getReposURL = `${config.host}/api/v5/user/repos`

const getPath = (url, params) => {
  Object.keys(params).map(key => {
    url = url.replace(new RegExp(`:${key}`, 'g'), params[key])
  })
  return url
}

const httpFilter = async (request) => {
  return new Promise((resolve, reject) => {
    request
      .then((data) => {
        resolve(data)
      })
      .catch(async err => {
        if (err.response.status === 401) {
          router.push({ name: 'login' })
        }
        reject(err)
      })
  })
}

export const host = config.host

export const login = async (loginInfo) => {
  return Get.basic(getUserInfoURL, {
    access_token: loginInfo.secretToken
  })
}

export const fetchNotifications = async ({
  page = 1,
  type = 'referer',
  unread = false,
  participating = false
} = {}) => {
  return httpFilter(Get(notificationURL, {
    access_token: store.state.user.accessToken,
    unread,
    participating,
    type,
    page,
    per_page: store.state.notify.listPerPage
  }))
}

/**
 * 设置消息已读
 * @param {String|Number} id 通知 ID
 */
export const setNoticeRead = async (id) => {
  const url = getPath(setReadNoticeURL, { id })
  return httpFilter(Patch(url, {
    access_token: store.state.user.accessToken
  }))
}

export const setUserMessageRead = async (id) => {
  const url = getPath(setReadUserMessageURL, { id })
  return httpFilter(Patch(url, {
    access_token: store.state.user.accessToken
  }))
}

/* eslint-disable camelcase */
export const getUserMessages = async ({
  unread = false,
  ids = [],
  page = 1,
  per_page = store.state.notify.listPerPage
} = {}) => {
  return httpFilter(Get(getUserMessageURL, {
    access_token: store.state.user.accessToken,
    ids,
    unread,
    page,
    per_page
  }))
}

/**
 * @param {Object} params 接口参数
 * @param {Number} [params.page] 获取分页数
 * @param {Number} [params.per_page] 每页数量
 * @param {String} [params.type] 筛选用户仓库: 其创建(owner)、个人(personal)、其为成员(member)、公开(public)、私有(private)，
 * 不能与 visibility 或 affiliation 参数一并使用，否则会报 422 错误
 * @param {String} [params.sort] 排序方式: 创建时间(created)，更新时间(updated)，最后推送时间(pushed)，仓库所属与名称(full_name)。
 * 默认: full_name
 * @returns {Promise} axios 请求的 promise 对象
 */
export const getRepos = async ({
  page = 1,
  per_page = 20,
  type = 'owner',
  sort = 'full_name'
} = {}) => {
  return httpFilter(Get(getReposURL, {
    access_token: store.state.user.accessToken,
    type,
    sort,
    page,
    per_page
  }))
}

/**
 * @param {Object} params 接口参数
 * @param {String} params.namespace 仓库 namespace, 如 `owner/repo`
 * @param {Number} [params.page] 获取分页数
 * @param {Number} [params.per_page] 每页数量
 * @returns {Promise} axios 请求的 promise 对象
 */
export const getIssues = async ({
  namespace,
  page = 1,
  per_page = 20
} = {}) => {
  if (!namespace) return Promise.reject(new Error({message: 'getIssues -> namespace 错误'}))
  const [owner, repo] = namespace.split('/')
  const url = getPath(getIssuesURL, { owner, repo })
  return httpFilter(Get(url, {
    access_token: store.state.user.accessToken,
    page,
    per_page
  }))
}

/**
 * @param {Object} params 接口参数
 * @param {String} params.namespace 仓库 namespace, 如 `owner/repo`
 * @param {Number} params.number issue 的 number 值
 * @returns {Promise} axios 请求的 promise 对象
 */
export const getIssue = async ({
  namespace,
  number
} = {}) => {
  if (!namespace) return Promise.reject(new Error({message: 'getIssue -> namespace 错误'}))
  if (!number) return Promise.reject(new Error({message: 'getIssue -> number 错误'}))
  const [owner, repo] = namespace.split('/')
  const url = getPath(getIssueURL, {
    owner,
    repo,
    number
  })
  return httpFilter(Get(url, {
    access_token: store.state.user.accessToken
  }))
}

/**
 * @param {Object} params 接口参数
 * @param {String} params.url 获取 comments 的接口
 * @param {Number} [params.page] 获取分页数
 * @param {Number} [params.per_page] 每页数量
 * @returns {Promise} axios 请求的 promise 对象
 */
export const getComments = async ({
  url,
  page = 1,
  per_page = 20
} = {}) => {
  if (!url) return Promise.reject(new Error({message: 'getComments -> url 错误'}))
  return Get(url, {
    page,
    per_page,
    access_token: store.state.user.accessToken
  })
}
